class SystemHelper {
  getUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户信息的用途
        success(res) {
          resolve(res.userInfo);
        },
        fail(err) {
          reject(err);
        },
      });
    });
  }

  getSettings() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: resolve,
        fail: reject,
      });
    });
  }
  openSetting() {
    return new Promise((resolve, reject) => {
      wx.openSetting({
        success: resolve,
        fail: reject,
      });
    });
  }

  authorize(scope) {
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope: scope,
        success: resolve,
        fail: reject,
      });
    });
  }

  ensureAuthorize(scope) {
    return this.getSettings()
      .then((res) => (res.authSetting[scope] ? 'ok' : this.authorize(scope)))
      .catch((_err) => this.openSetting());
  }

  saveImageToPhotosAlbum(filePath) {
    return new Promise((resovle, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success: resovle,
        fail: reject,
      });
    });
  }

  saveToTmpFile(data, fileName) {
    return new Promise((resolve, reject) => {
      const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
      wx.getFileSystemManager().writeFile({
        filePath: filePath,
        data: data,
        encoding: 'binary',
        success: function () {
          resolve(filePath);
        },
        fail: reject,
      });
    });
  }

  downloadFile(url) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: url,
        success(res) {
          if (res.statusCode === 200) {
            resolve(res.tempFilePath);
          } else {
            reject(res.errMsg);
          }
        },
        fail: reject,
      });
    });
  }

  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: resolve,
        fail: reject,
      });
    });
  }
}

const instance = new SystemHelper();
module.exports = instance;
